/**
 * 
 */
package template.page.admin;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.SortedSet;

import org.apache.click.control.AbstractLink;
import org.apache.click.control.ActionLink;
import org.apache.click.control.Column;
import org.apache.click.control.Form;
import org.apache.click.control.HiddenField;
import org.apache.click.control.Option;
import org.apache.click.control.Select;
import org.apache.click.control.Submit;
import org.apache.click.control.Table;
import org.apache.click.dataprovider.DataProvider;
import org.apache.click.extras.control.DateField;
import org.apache.click.extras.control.LinkDecorator;
import org.apache.click.extras.control.PickList;
import org.apache.click.util.Bindable;

import template.page.BorderPage;
import cvcg.model.AttendingPlayer;
import cvcg.model.Game;
import cvcg.model.GameSession;
import cvcg.util.Top5ResultDecorator;
import cvcg.util.VoteResultDecorator;

/**
 * @author jaracje
 *
 */
@SuppressWarnings("serial")
public class EditGameSession extends BorderPage 
{
	public String title = "Edit Game Session";
	private Form gameSessionForm = new Form("gameSessionForm");
	private Table attendingPlayerTable = new Table("attendingPlayerTable");
	private Table voteTable = new Table("voteTable");
	private Table top5Table = new Table("top5Table");
	private ActionLink deletePlayerLink = new ActionLink("Delete",this,"onDeletePlayerClick");
	private HiddenField idField = new HiddenField("id",Long.class);
	private Select statusSelect = new Select("status");
	private PickList playedGamesPickList = new PickList("playedGamesPickList","Played Games");
	
	@Bindable protected Long id;
		
	@SuppressWarnings("rawtypes")
	public EditGameSession() 
	{
		addControl(gameSessionForm);
        gameSessionForm.add(idField);

        DateField dateField = new DateField("date", true);
        dateField.setShowTime(true);
        dateField.setFormatPattern("dd/MM/yyyy HH:mm");
        gameSessionForm.add(dateField);
        gameSessionForm.add(statusSelect);
        gameSessionForm.add(playedGamesPickList);
        gameSessionForm.add(new Submit("ok", " OK ", this, "onOkClicked"));
        gameSessionForm.add(new Submit("cancel", this, "onCancelClicked"));        

        statusSelect.setDataProvider(new DataProvider() {

            @SuppressWarnings("unchecked")
			public List getData() {
                List optionList = new ArrayList(3);
                optionList.add(new Option(GameSession.STATUS_PHASE1));
                optionList.add(new Option(GameSession.STATUS_PHASE2));
                optionList.add(new Option(GameSession.STATUS_CLOSED));
                return optionList;
            }
        });
                       
        addControl(voteTable);
        addControl(top5Table);
	}
		
	@Override
    public void onGet() {

        if (id != null) 
        {
        	GameSession gameSession = gameSessionService.getGameSessionById(id);        	
        	gameSessionForm.copyFrom(gameSession);
        	buildVoteTable();
        	buildTop5Table();    		
        	for (Game game : gameSession.getPlayedGames()) 
        	{
        		playedGamesPickList.addSelectedValue(game.getId().toString());
        	}

        }
    }

	/* (non-Javadoc)
	 * @see org.apache.click.Page#onInit()
	 */
	@SuppressWarnings("rawtypes")
	@Override
	public void onInit() {
    	DataProvider playedGamesPickListDataProvider = new DataProvider() 
		{
			public List getData() 
			{
				List<Game> allGames = gameSessionService.getAllGames();   
				List<Option> gameOptions = new ArrayList<Option>();
		        
		        for (Game game : allGames) 
		        {
		        	gameOptions.add(new Option(game.getId(),game.getName()));
				}
				return gameOptions;
			}
		};
		playedGamesPickList.setDataProvider(playedGamesPickListDataProvider);
		super.onInit();
	}

	/**
     * Handle the OK button click event.
     *
     * @return true
     */
    public boolean onOkClicked() {
        if (gameSessionForm.isValid()) 
        {
        	Long idValue = (Long) idField.getValueObject();
        	gameSessionService.saveGameSession(idValue, gameSessionForm,playedGamesPickList);
        	setRedirect(ManageGameSessions.class);
        	return true;
        }
        
        return false;
    }

    /**
     * Handle the Cancel button click event.
     *
     * @return false
     */
    public boolean onCancelClicked() {
    	setRedirect(ManageGameSessions.class);
        return true;
    }

    @SuppressWarnings("rawtypes")
    public void buildAttendingPlayerTable()
    {
        attendingPlayerTable.setClass(Table.CLASS_ITS);       
        attendingPlayerTable.setShowBanner(false);
        attendingPlayerTable.setSortable(false);
		
        attendingPlayerTable.addColumn(new Column("id"));
		Column dateColumn = new Column("joinDate");
		dateColumn.setFormat("{0,date,dd/MM/yyyy HH:mm}");
		attendingPlayerTable.addColumn(dateColumn);
		attendingPlayerTable.addColumn(new Column("player.name"));
		
		
        Column column = new Column("Action");
        column.setTextAlign("center");
        AbstractLink[] links = new AbstractLink[] { deletePlayerLink };
        column.setDecorator(new LinkDecorator(attendingPlayerTable, links, "id"));
        column.setSortable(false);
        
        // Table rowList will be populated through a DataProvider which loads
        // data on demand.
        attendingPlayerTable.setDataProvider(new DataProvider() {

            public Collection getData() {
            	GameSession gameSession = getGameSessionService().getGameSessionById(id);
            	if (gameSession!=null) 
            	{
            		return gameSession.getAttendingPlayers();
            	}
            	return null;
            }
        });

    }
    
    @SuppressWarnings("rawtypes")
    public void buildVoteTable()
    {
    	voteTable.setClass(Table.CLASS_ITS);    	
    	voteTable.setShowBanner(false);
    	voteTable.setSortable(false);
		
    	GameSession gameSession = getGameSessionService().getGameSessionById(id);
    	SortedSet<AttendingPlayer> attendingPlayers = gameSession.getAttendingPlayers();
    	String playerName;
    	voteTable.addColumn(new Column("gameName"));
    	Column playerCol;    	
    	for (AttendingPlayer attendingPlayer : attendingPlayers) 
    	{
			playerName = attendingPlayer.getPlayerName();
			playerCol = new Column(playerName);
			playerCol.setTextAlign("center");
			playerCol.setDecorator(new VoteResultDecorator(playerName));
			voteTable.addColumn(playerCol);
		}    	
    	Column votes = new Column("votes");
    	votes.setTextAlign("center");
    	voteTable.addColumn(votes);
    	voteTable.setSortedColumn("gameName");    	
    	
        voteTable.setDataProvider(new DataProvider() {

            public Collection getData() {
            	return gameSessionService.getVoteResultForGameSession(id);
            	
            }
        });
    }
    
    @SuppressWarnings("rawtypes")
    public void buildTop5Table()
    {
    	top5Table.setClass(Table.CLASS_ITS);    	
    	top5Table.setShowBanner(false);
    	top5Table.setSortable(false);
		
    	GameSession gameSession = getGameSessionService().getGameSessionById(id);
    	SortedSet<AttendingPlayer> attendingPlayers = gameSession.getAttendingPlayers();
    	String playerName;
    	top5Table.addColumn(new Column("gameName"));
    	Column playerCol;    	
    	for (AttendingPlayer attendingPlayer : attendingPlayers) 
    	{
			playerName = attendingPlayer.getPlayerName();
			playerCol = new Column(playerName);
			playerCol.setTextAlign("center");
			playerCol.setDecorator(new Top5ResultDecorator(playerName));
			top5Table.addColumn(playerCol);
		}    	
    	Column points = new Column("points");
    	points.setTextAlign("center");
    	top5Table.addColumn(points);
    	top5Table.setSortedColumn("points");
    	top5Table.setSortedAscending(false);
    	
    	top5Table.setDataProvider(new DataProvider() {

            public Collection getData() 
            {
            	return gameSessionService.getTop5ResultForGameSession(id);            
            }
        });
    }
}
